package bingo.rpc.framework.cluster.impl;

import bingo.rpc.framework.cluster.ClusterStrategy;
import bingo.rpc.framework.model.ProviderService;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.RandomUtils;

import java.util.List;

/**
 * 加权随机软负载均衡算法
 *
 * @author hujinsheng
 * @project bingo
 * @create 2017-12-14 13:51
 **/
public class WeightRandomClusterStrategyImpl implements ClusterStrategy {
    @Override
    public ProviderService select(List<ProviderService> providerServices) {
        //存放加权后的服务提供者列表
        List<ProviderService> providerServiceList= Lists.newArrayList();
        for(ProviderService provider:providerServices){
            int weight=provider.getWeight();
            for(int i=0;i<weight;i++){
                providerServiceList.add(provider.copy());
            }
        }
        int MAX_LEN=providerServiceList.size();
        int index=RandomUtils.nextInt(0,MAX_LEN-1);
        return providerServiceList.get(index);
    }
}
